#pragma once

#include <iostream>
#include <vector>
#include <pthread.h>
#include <string>
#include <queue>
#include "task.hpp"

using namespace std;

// 描述线程
struct threadinfo
{
    pthread_t tid;
    string name;
};

static int default_num = 10; // 默认线程个数

template <class T>
class threadpool
{
private:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void Unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }
    void Sleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }
    bool isQueueEmpty()
    {
        return _q.empty();
    }
    string GetName(pthread_t tid)
    {
        for(auto& ti : _threads)
        {
            if(ti.tid == tid)
                return ti.name;
        }
        return "None";
    }
    T Pop()
    {
        T t = _q.front();
        _q.pop();
        return t;
    }

public:
    threadpool(int num = default_num)
        : _threads(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    static void *routine(void *args)
    {
        threadpool<T> *tp = static_cast<threadpool<T> *>(args);
        string name = tp->GetName(pthread_self());
        while (true)
        {
            tp->Lock();
            while (tp->isQueueEmpty())
            {
                tp->Sleep();
            }
            T task = tp->Pop();
            tp->Unlock();
            task.run();            
        }
    }

    void Start()
    {
        int num = _threads.size();
        for (int i = 0; i < num; i++)
        {
            _threads[i].name = "thread" + to_string(i + 1);
            pthread_create(&(_threads[i].tid), nullptr, routine, this);
        }
    }

    void Push(T &task)
    {
        Lock();
        _q.push(task);
        Wakeup();
        Unlock();
    }

    ~threadpool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    vector<threadinfo> _threads; // 将线程用vector组织起来
    queue<T> _q;                 // 用于存放任务，供线程消费

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
};